package com.thh.datamonitor.controller;

import com.thh.common.core.controller.BaseController;
import com.thh.common.core.model.AjaxResult;
import com.thh.datamonitor.dto.ExcuteAndShowExecSqlDataDto;
import com.thh.datamonitor.dto.ExcuteAndShowShowDto;
import com.thh.datamonitor.dto.TableInfoListDto;
import com.thh.datamonitor.entity.TmdDatabase;
import com.thh.datamonitor.executor.AbstractDbExecutor;
import com.thh.datamonitor.executor.DbExecutorFactory;
import com.thh.datamonitor.param.ExcuteAndShowExecSqlDataParam;
import com.thh.datamonitor.param.TmdSQLShowParam;
import com.thh.datamonitor.service.ITmdDatabaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * excuteAndShowController
 * @author thh
 * @date 2022-06-23
 */
@Controller
@RequestMapping("/datamonitor/excuteAndShow")
public class ExcuteAndShowController extends BaseController
{
    private String prefix = "datamonitor/excuteAndShow";

    @Autowired
    private ITmdDatabaseService tmdDatabaseService;

    @Autowired
    DbExecutorFactory dbExecutorFactory;


    @GetMapping( )
    public String excuteAndShow(Model model){
        return prefix + "/excuteAndShow";
    }


    /**
     * 执行sql
     */
    @PostMapping("/executeSql")
    @ResponseBody
    public AjaxResult executeSql(ExcuteAndShowExecSqlDataParam excuteAndShowExecSqlDataParam) throws Exception {
        TmdDatabase database = tmdDatabaseService.getMyDatabaseId(excuteAndShowExecSqlDataParam.getDatabaseId());
        AbstractDbExecutor dbExecutor = dbExecutorFactory.getDbExecutor(database.getDatabaseType());
        ExcuteAndShowExecSqlDataDto excuteAndShowExecSqlDataDto = dbExecutor.execSql(database, excuteAndShowExecSqlDataParam);
        return success(excuteAndShowExecSqlDataDto);
    }


    /**
     * 查询数据
     */
    @PostMapping("/list")
    @ResponseBody
    public AjaxResult excuteAndShowList(TmdSQLShowParam tmdSQLShowParam) throws Exception {
        String databaseId = tmdSQLShowParam.getDatabaseId();
        TmdDatabase database = tmdDatabaseService.getMyDatabaseId(databaseId);
        String databaseType = database.getDatabaseType();
        AbstractDbExecutor dbExecutor = dbExecutorFactory.getDbExecutor(databaseType);
        ExcuteAndShowShowDto excuteAndShowShowDto = dbExecutor.excuteAndShowList(database, tmdSQLShowParam);
        return AjaxResult.success(excuteAndShowShowDto);
    }
}
